﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using DevComponents.Editors;
using DevComponents.DotNetBar;
using DevComponents.DotNetBar.Metro;
using ProductManagement.Ultilities;

namespace ProductManagement.Presentation_Layer
{
    public partial class MainForm : MetroForm
    {
        #region Variables

        private ProductManagementClassesDataContext db = new ProductManagementClassesDataContext();
        private Validator validator = new Validator();

        #endregion

        #region Constructors

        public MainForm()
        {
            InitializeComponent();
        }

        #endregion

        #region Methods

        public static void DisplayExportImportInfo(int reportID, MainForm mainForm)
        {
            mainForm.dgvImportExport.DataSource = mainForm.db.sp_GetReportDetails(reportID);
            int count = (int)mainForm.db.sp_GetReportDetailsCount(reportID).SingleOrDefault().dem;
            for (int i = 0; i < count; i++)
            {
                mainForm.dgvImportExport[0, i].Value = i + 1;
            }
            decimal sum = (decimal)mainForm.db.sp_GetReportSumPrice(reportID).SingleOrDefault().tong;
            mainForm.db.sp_UpdateReportSumPrice(reportID, sum);
            mainForm.db.SubmitChanges();
            mainForm.lblSumPrice.Text = "<b>Tổng giá trị nhập / xuất: </b>" + sum.ToString();
        }

        #endregion

        #region Events Handling

        private void cbxSearchType_SelectionChangeCommitted(object sender, EventArgs e)
        {
            int count = cbxSearchRange.Items.Count;
            if (count > 0)
            {
                for (int i = 0; i < count; i++)
                    ((ComboItem)cbxSearchRange.Items[i]).Dispose();
                cbxSearchRange.Items.Clear();
            }
            if (cbxSearchType.SelectedItem == ciSearchName || cbxSearchType.SelectedItem == ciSearchYear)
            {
                cbxSearchRange.Visible = false;
                txtSearchValue.Visible = true;
            }
            if (cbxSearchType.SelectedItem == ciSearchPrice)
            {
                txtSearchValue.Visible = false;
                cbxSearchRange.Visible = true;
                ComboItem[] items = new ComboItem[6];
                items[0] = new ComboItem("0 - 100000");
                items[1] = new ComboItem("100000 - 500000");
                items[2] = new ComboItem("500000 - 1000000");
                items[3] = new ComboItem("1000000 - 5000000");
                items[4] = new ComboItem("5000000 - 10000000");
                items[5] = new ComboItem("10000000 - up");
                for (int i = 0; i < 6; i++)
                {
                    cbxSearchRange.Items.Add(items[i]);
                }
            }
            if (cbxSearchType.SelectedItem == ciSearchQuantity)
            {
                txtSearchValue.Visible = false;
                cbxSearchRange.Visible = true;
                ComboItem[] items = new ComboItem[6];
                items[0] = new ComboItem("0 - 100");
                items[1] = new ComboItem("100 - 500");
                items[2] = new ComboItem("500 - 1000");
                items[3] = new ComboItem("1000 - 5000");
                items[4] = new ComboItem("5000 - 10000");
                items[5] = new ComboItem("10000 - up");
                for (int i = 0; i < 6; i++)
                {
                    cbxSearchRange.Items.Add(items[i]);
                }
            }
            if (cbxSearchType.SelectedItem == ciSearchState)
            {
                txtSearchValue.Visible = false;
                cbxSearchRange.Visible = true;
                ComboItem[] items = new ComboItem[2];
                items[0] = new ComboItem("Còn hàng");
                items[1] = new ComboItem("Hết hàng");
                for (int i = 0; i < 2; i++)
                {
                    cbxSearchRange.Items.Add(items[i]);
                }
            }
        }

        private void btnSearch_Click(object sender, EventArgs e)
        {
            if (cbxSearchType.SelectedItem == ciSearchName)
            {
                var searchResult = db.sp_SearchByName(txtSearchValue.Text);
                dgvGeneral.DataSource = searchResult;
            }
            if (cbxSearchType.SelectedItem == ciSearchPrice)
            {
                string tempText = cbxSearchRange.Text.Replace(" ", "");
                string[] rangeValues = tempText.Split('-');
                decimal min = Decimal.Parse(rangeValues[0]);
                try
                {
                    decimal max = Decimal.Parse(rangeValues[1]);
                    var searchResult = db.sp_SearchByPrice(min, max, 1);
                    dgvGeneral.DataSource = searchResult;
                }
                catch (FormatException)
                {
                    var searchResult = db.sp_SearchByPrice(min, 0, 2);
                    dgvGeneral.DataSource = searchResult;
                }
            }
            if (cbxSearchType.SelectedItem == ciSearchQuantity)
            {
                string tempText = cbxSearchRange.Text.Replace(" ", "");
                string[] rangeValues = tempText.Split('-');
                int min = Int32.Parse(rangeValues[0]);
                try
                {
                    int max = Int32.Parse(rangeValues[1]);
                    var searchResult = db.sp_SearchByQuantity(min, max, 1);
                    dgvGeneral.DataSource = searchResult;
                }
                catch (FormatException)
                {
                    var searchResult = db.sp_SearchByQuantity(min, 0, 2);
                    dgvGeneral.DataSource = searchResult;
                }
            }
            if (cbxSearchType.SelectedItem == ciSearchYear)
            {
                try
                {
                    int year = Int32.Parse(txtSearchValue.Text);
                    if (year > DateTime.Now.Year)
                        errorProvider1.SetError(txtSearchValue, "Năm sản xuất không được lớn hơn năm hiện tại!");
                    else if (year < 0)
                        errorProvider1.SetError(txtSearchValue, "Năm sản xuất phải lớn hơn 0!");
                    else
                    {
                        var searchResult = db.sp_SearchByYear(year);
                        dgvGeneral.DataSource = searchResult;
                    }
                }
                catch (FormatException)
                {
                    errorProvider1.SetError(txtSearchValue, "Năm sản xuất phải là số nguyên!");
                }
            }
            if (cbxSearchType.SelectedItem == ciSearchState)
            {
                var searchResult = db.sp_SearchByState(cbxSearchRange.Text);
                dgvGeneral.DataSource = searchResult;
            }
        }

        private void btnBackToGeneral_Click(object sender, EventArgs e)
        {
            cbxSearchRange.ResetText();
            cbxSearchType.ResetText();
            txtSearchValue.ResetText();
            var products = db.sp_GetAllProducts();
            dgvGeneral.DataSource = products;
        }

        private void stiGeneral_Click(object sender, EventArgs e)
        {
            var products = db.sp_GetAllProducts();
            dgvGeneral.DataSource = products;
        }

        private void stiHistory_Click(object sender, EventArgs e)
        {
            var reports = db.sp_GetAllReports();
            dgvAllReport.DataSource = reports;
        }

        private void btnDeleteProduct_Click(object sender, EventArgs e)
        {
            try
            {
                int rowIndex = dgvGeneral.SelectedCells[0].RowIndex;
                if (rowIndex >= 0)
                {
                    int productID = (int)dgvGeneral[0, rowIndex].Value;
                    DialogResult dr = MessageBoxEx.Show("Bạn có muốn xóa sản phẩm này?", "Thông báo", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
                    if (dr == DialogResult.Yes)
                    {
                        db.sp_DeleteProduct(productID);
                        MessageBoxEx.Show("Xóa sản phẩm thành công", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }
                    db.SubmitChanges();
                    dgvGeneral.DataSource = db.sp_GetAllProducts();
                }
            }
            catch (Exception ex)
            {
                MessageBoxEx.Show(ex.ToString());
            }
        }

        private void btnEditProduct_Click(object sender, EventArgs e)
        {
            try
            {
                int rowIndex = dgvGeneral.SelectedCells[0].RowIndex;
                if (rowIndex >= 0)
                {
                    int productID = (int)dgvGeneral[0, rowIndex].Value;
                    EditForm editForm = new EditForm(productID);
                    editForm.Show();
                }
            }
            catch (ArgumentOutOfRangeException)
            {

            }
            catch (Exception ex)
            {
                MessageBoxEx.Show(ex.ToString());
            }
        }

        private void tsmiEditProduct_Click(object sender, EventArgs e)
        {
            try
            {
                int rowIndex = dgvGeneral.SelectedCells[0].RowIndex;
                if (rowIndex >= 0)
                {
                    int productID = (int)dgvGeneral[0, rowIndex].Value;
                    EditForm editForm = new EditForm(productID);
                    editForm.Show();
                }
            }
            catch (Exception ex)
            {
                MessageBoxEx.Show(ex.ToString());
            }
        }

        private void tsmiDeleteProduct_Click(object sender, EventArgs e)
        {
            try
            {
                int rowIndex = dgvGeneral.SelectedCells[0].RowIndex;
                if (rowIndex >= 0)
                {
                    int productID = (int)dgvGeneral[0, rowIndex].Value;
                    DialogResult dr = MessageBoxEx.Show("Bạn có muốn xóa sản phẩm này?", "Thông báo", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
                    if (dr == DialogResult.Yes)
                    {
                        db.sp_DeleteProduct(productID);
                        MessageBoxEx.Show("Xóa sản phẩm thành công", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }
                    db.SubmitChanges();
                    dgvGeneral.DataSource = db.sp_GetAllProducts();
                }
            }
            catch (Exception ex)
            {
                MessageBoxEx.Show(ex.ToString());
            }
        }

        private void MainForm_Load(object sender, EventArgs e)
        {
            dgvGeneral.DataSource = db.sp_GetAllProducts();
        }

        private void btnImport_Click(object sender, EventArgs e)
        {
            DateTime date = DateTime.Now;
            db.sp_InsertReport("Nhập hàng", date);
            int reportID = db.sp_GetReportID("Nhập hàng", date).SingleOrDefault().id;
            ImportForm importForm = new ImportForm(reportID, this);
            importForm.Show();
        }

        private void btnExport_Click(object sender, EventArgs e)
        {
            DateTime date = DateTime.Now;
            db.sp_InsertReport("Xuất hàng", date);
            int reportID = db.sp_GetReportID("Xuất hàng", date).SingleOrDefault().id;
            ExportForm exportForm = new ExportForm(reportID, this);
            exportForm.Show();
        }

        private void btnDeleteReport_Click(object sender, EventArgs e)
        {
            try
            {
                int rowIndex = dgvAllReport.SelectedCells[0].RowIndex;
                int reportID = (int)dgvAllReport[0, rowIndex].Value;
                DialogResult dr = MessageBoxEx.Show("Bạn có muốn xóa báo cáo đã chọn?", "Thông báo", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
                if (dr == DialogResult.Yes)
                {
                    db.sp_DeleteReport(reportID);
                    MessageBoxEx.Show("Xóa báo cáo thành công!", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
                dgvAllReport.DataSource = db.sp_GetAllReports();
                db.SubmitChanges();
            }
            catch (ArgumentOutOfRangeException)
            {

            }
            catch (Exception ex)
            {
                MessageBoxEx.Show(ex.ToString(), "Ngoại lệ", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void tsmiDeleteReport_Click(object sender, EventArgs e)
        {
            try
            {
                int rowIndex = dgvAllReport.SelectedCells[0].RowIndex;
                int reportID = (int)dgvAllReport[0, rowIndex].Value;
                DialogResult dr = MessageBoxEx.Show("Bạn có muốn xóa báo cáo đã chọn?", "Thông báo", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
                if (dr == DialogResult.Yes)
                {
                    db.sp_DeleteReport(reportID);
                    MessageBoxEx.Show("Xóa báo cáo thành công!", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
                dgvAllReport.DataSource = db.sp_GetAllReports();
                db.SubmitChanges();
            }
            catch (Exception ex)
            {
                MessageBoxEx.Show(ex.ToString(), "Ngoại lệ", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void stiImportExport_Click(object sender, EventArgs e)
        {
            DataTable dt = new DataTable();
            dt.Columns.Add("name");
            dt.Columns.Add("price");
            dt.Columns.Add("quantity");
            dgvImportExport.DataSource = dt;
        }

        private void btnReportDetail_Click(object sender, EventArgs e)
        {
            try
            {
                int rowIndex = dgvAllReport.SelectedCells[0].RowIndex;
                int reportID = (int)dgvAllReport[0, rowIndex].Value;
                string reportTask = dgvAllReport[1, rowIndex].Value.ToString();
                ReportForm reportForm = new ReportForm(reportID, reportTask);
                reportForm.Show();
            }
            catch (ArgumentOutOfRangeException)
            {

            }
            catch (Exception ex)
            {
                MessageBoxEx.Show(ex.ToString(), "Ngoại lệ", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void tsmiDeleteDetail_Click(object sender, EventArgs e)
        {

        }

        #endregion
    }
}
